package com.lucker.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.NamedThreadLocal;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.lucker.common.request.RequestHeader;
import com.lucker.common.util.IPUtil;
import com.lucker.common.util.RequestUtil;
import com.lucker.ds.model.UserToken;
import com.lucker.framework.constant.ResponseResultModel;
import com.lucker.service.user.UserTokenService;

public class LogInterceptors implements HandlerInterceptor {
	private static Logger			LOGGER					= LoggerFactory.getLogger(LogInterceptors.class);
	//private NamedThreadLocal<Long>	startTimeThreadLocal	= new NamedThreadLocal<Long>("StopWatch-StartTime");
	
	
	@Autowired
	private UserTokenService  userTokenService;

	@SuppressWarnings("unused")
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String ip = IPUtil.getIPAddress(request);
		RequestHeader reqHeader = null;
		//LOGGER.error("请求地址 {} {}://{}:{}{} 参数：{} client ip :{}", new Object[] { request.getMethod(), request.getScheme(), request.getLocalAddr(), request.getServerPort(), request.getRequestURI(), (NetworkUtil.getLocalIP()) });
		//对配置的URL进行登录校验, 如果USERID,USERTOKEN同时存在,则两个同时进行判断，如果没有USERID，则用TOKEN进行判断
        try {
        	
			if(true) {
				return true;
			}
			
			reqHeader = RequestUtil.getReqeustHeader(request);
			response.setCharacterEncoding("utf-8");
			if(reqHeader == null) {
				Object ret = JSONObject.toJSON(new ResponseResultModel<>(21991,"用户鉴权失败,未提交 REQEUST HEADER 信息",HttpStatus.OK));
				PrintWriter writer = response.getWriter();
				writer.append(ret.toString());
				writer.close();
				return Boolean.FALSE;
			}
			
					
			if(StringUtils.isBlank(reqHeader.getUserToken())) {
				Object ret = JSONObject.toJSON(new ResponseResultModel<>(21992,"用户鉴权失败,未提交 USER TOKEN 信息",HttpStatus.OK));
				PrintWriter writer = response.getWriter();
				writer.append(ret.toString());
				writer.close();
				return Boolean.FALSE;
			}
			
			
			UserToken _utk = new UserToken();
			_utk.setUserToken(reqHeader.getUserToken());
			if(reqHeader.getUserId() != null && reqHeader.getUserId() > 0) {
				_utk.setUserId(reqHeader.getUserId());
			}	
			
			if(userTokenService.isLogin(_utk)) {
				return Boolean.TRUE;
			}else {
				Object ret = JSONObject.toJSON(new ResponseResultModel<>(91993,"用户鉴权失败,用户登录验证过期,请重新登录",HttpStatus.OK));
				PrintWriter writer = response.getWriter();
				writer.append(ret.toString());
				writer.close();
				return Boolean.FALSE;
			}
        }catch(Exception e) {
        	LOGGER.error("LogInterceptors 鉴权异常 ", e);
        	Object ret = JSONObject.toJSON(new ResponseResultModel<>(21994,"鉴权异常, 请重试", HttpStatus.OK));
			PrintWriter writer = response.getWriter();
			writer.append(ret.toString());
			writer.close();
			return Boolean.FALSE;
        }
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		HttpServletRequest req = request;
		
//		System.out.println(req.getMethod());
//        //获取项目名称
//        System.out.println(req.getContextPath());
//        //获取完整请求路径
//        System.out.println(req.getRequestURL());
//        //获取除了域名外的请求数据
//        System.out.println(req.getRequestURI());
//        //获取请求参数
//        System.out.println(req.getQueryString());
//        System.out.println("以下为请求头信息: ");
//        //获取请求头
//        String header = req.getHeader("user-Agent");
//        System.out.println(header);
//        header = header.toLowerCase();
//        //根据请求头数据判断浏览器类型
//        if(header.contains("chrome")){
//            System.out.println("您的访问浏览器为谷歌浏览器");
//        }else if(header.contains("msie")){
//            System.out.println("您的访问浏览器为IE浏览器");
//        }else if(header.contains("firefox")){
//            System.out.println("您的访问浏览器为火狐浏览器");
//        }else{
//            System.out.println("您的访问浏览器为其它浏览器");
//        }
//        
//        System.out.println("----------------------------------------------------------");
//        //获取所有的消息头名称
//        Enumeration<String> headerNames = req.getHeaderNames();
//        //获取获取的消息头名称，获取对应的值，并输出
//        while(headerNames.hasMoreElements()){
//            String nextElement = headerNames.nextElement();
//            System.out.println(nextElement+":"+req.getHeader(nextElement));
//        }
//        System.out.println("----------------------------------------------------------");
//        //根据名称获取此重名的所有数据
//        Enumeration<String> headers = req.getHeaders("accept");
//        while (headers.hasMoreElements()) {
//            String string = (String) headers.nextElement();
//            System.out.println(string);
//        }
//        
        
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//		long endTime = System.currentTimeMillis();//2、结束时间  
//		long beginTime = startTimeThreadLocal.get();//得到线程绑定的局部变量（开始时间）  
//		long consumeTime = endTime - beginTime;//3、消耗的时间  
//		if (consumeTime > 0) {//此处认为处理时间超过500毫秒的请求为慢请求  
//			//TODO 记录到日志文件  
//			//LOGGER.error("响应地址 {} {}://{}:{}{}耗时：{}", new Object[] { request.getMethod(), request.getScheme(), request.getLocalAddr(), request.getServerPort(), request.getRequestURI(), consumeTime });
//		}
	}
}

